﻿using FantasyWereld.Common;
using FantasyWereld.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI.Notifications;
using Windows.Web.Syndication;

namespace FantasyWereld.Code
{
    class BadgeUpdater
    {
        /// <summary>
        /// Update badge info
        /// </summary>
        public static async Task UpdateBadgeInfoAsync(XmlDocument _allItems)
        {
            // Fetch template
            XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
            XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");

            int newValue = await CountFantasyWereldNewItemsAsync(_allItems);

            // Set roaming value to new value
            ApplicationData.Current.RoamingSettings.Values["BadgeValue"] = newValue;

            if (newValue == 0)
            {
                // Something went wrong so we will clear the value just for safety
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
            }
            else
            {
                // Set badge value
                badgeElement.SetAttribute("value", newValue.ToString());
                BadgeNotification badge = new BadgeNotification(badgeXml);
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
            }
        }

        /// <summary>
        /// Count new items on FantasyWereld website
        /// This is a copy of the Main program function in FWDataSource class file
        /// </summary>
        private static async Task<int> CountFantasyWereldNewItemsAsync(XmlDocument _allItems)
        {
            try
            {
                // Retrieve RSS feed information from Fantasy Wereld webserver
                return await ProcessItemsInFeedAsync(Constants.RSSFEED_LATEST, _allItems);
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// Count number of items in a feed 
        /// </summary>
        /// <param name="feedName"></param>
        /// <param name="_allReviews"></param>
        /// <returns></returns>
        private static async Task<int> ProcessItemsInFeedAsync(string feedName, XmlDocument _allItems)
        {
            int numberOfItems = 0;
            var myFeed = await Utility.GetRSSFeedAsync(feedName);

            XmlDocument newsList = new XmlDocument();

            newsList.LoadXml(Constants.XML_BASE_FILE);
                        
            foreach (var channel in myFeed)
            {
                foreach (var item in channel.Items)
                {
                    // Search on Link
                    var nodeList = _allItems.GetElementsByTagName("Link");
                    XmlElement node = null;

                    if (nodeList.Count > 0)
                        // Find the node with this id from the data file
                        node = FindNode(nodeList, item.Link);

                    if ((node == null) && !item.Link.Contains("nieuwsbericht"))
                        numberOfItems += 1;

                    // Create a new root node
                    XmlElement root = newsList.DocumentElement;
                    XmlElement newElem = newsList.CreateElement("news");
                    root.AppendChild(newElem);

                    // Create an element node for description
                    XmlElement newElemDetail = newsList.CreateElement("newsContent");
                    newElemDetail.InnerText = Utility.CleanupHTML(item.Description);
                    newElem.AppendChild(newElemDetail);

                    // Create an new element node for publication date
                    newElemDetail = newsList.CreateElement("newsDate");
                    if (item.pubDate != "")
                    {
                        var myDate = Convert.ToDateTime(item.pubDate);
                        newElemDetail.InnerText = myDate.ToString("dd-MM-yyyy");
                    }
                    else
                        newElemDetail.InnerText = "";
                    newElem.AppendChild(newElemDetail);

                    // Create an new element node for link
                    newElemDetail = newsList.CreateElement("newsLink");
                    newElemDetail.InnerText = item.Link;
                    newElem.AppendChild(newElemDetail);

                    // Create an element node for title
                    newElemDetail = newsList.CreateElement("newsTitle");
                    newElemDetail.InnerText = item.Title;
                    newElem.AppendChild(newElemDetail);
                }
            }

            FWDataSource.UpdateNews(newsList);

            return numberOfItems;
        }

        private static XmlElement FindNode(XmlNodeList list, string nodeName)
        {
            if (list.Count > 0)
                foreach (XmlElement node in list)
                    if (node.InnerText.Equals(nodeName)) return node;
            return null;
        }

        public static void UpdateNewsItem()
        {
            // Determine current news iten
            int currentNews = NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsIndex;

            currentNews++;

            XmlDocument newsList = FWDataSource.GetNews;
            if (newsList.ChildNodes.Count > 0)
                if (newsList.ChildNodes[1].ChildNodes.Count > 0)
                {
                    if (currentNews >= newsList.ChildNodes[1].ChildNodes.Count)
                        currentNews = 0;

                    var x = newsList.ChildNodes[1].ChildNodes[currentNews];

                    NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsIndex = currentNews;
                    NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsContent = x.ChildNodes[0].InnerText;
                    NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsDate = x.ChildNodes[1].InnerText;
                    NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsLink = x.ChildNodes[2].InnerText;
                    NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsTitle = x.ChildNodes[3].InnerText;
                }
        }

        public static string GetNewsLink()
        {
            // Determine current news iten
            int currentNews = NavDataSource._NavDataSource.AllGroups.FirstOrDefault().NewsIndex;

            XmlDocument newsList = FWDataSource.GetNews;

            if (newsList.ChildNodes[1].ChildNodes.Count > 0)
                return newsList.ChildNodes[1].ChildNodes[currentNews].ChildNodes[2].InnerText;
            else
                return "";
        }

    }
}
